#!/usr/bin/env python
# coding: utf-8

import web
from lxml import etree
import os

urls = (
    "/(index)", 'Index',
    "/(add)", 'Add',
    "/(logon)", 'Logon',
    "/(reset)", 'Reset',
    "/(edit)", 'Edit',
    "/(delete)", 'Delete',
    "/(setting)", 'Setting',
    "/()", 'Index'
    )

app = web.application(urls, globals())
app.wsgifunc()
#web.config.debug = False

if web.config.get('_session') is None:
    session = web.session.Session(app, web.session.DiskStore('sessions'), {'name':'anonymous', 'logged':False, 'current':'0'})
    web.config._session = session
else:
    session = web.config._session
    print session.get('name', 'nothing')

register = False
    
t_globals = {
    'datestr': web.datestr,
    'session': session
}
render = web.template.render('templates', base='base', globals=t_globals)
db = web.database(dbn='mysql', user='root', pw='asdfoplk', db='blog_shema')
    
class Index:
    def GET(self, name):
        limit = 5
        param = web.input()
        try:
            page = int(param.get('id', 1))
            session.current = page
            total = db.query("SELECT COUNT(*) FROM blog_posts")
            total = total[0]['COUNT(*)']
            pages = total/limit + 1
            offset = total - page*limit;
            
            if -limit < offset < 0:
                limit = -offset
                offset = 0

            if total < offset or offset < 0:
                raise Exception(self, 'OLOLOLOLO!!!!')

            views = db.select('blog_posts', limit=limit, offset=offset)
            views = list(views)
            login = web.config._session.get('name', 'anon')
            return render.view(self, login, views[::-1], pages)
        except:
            return render.error(self, 'Error number page or connecting to BD ( check correct password )')

class Not_found:
    def GET(self, name):
        return "404, not found :("

class Add:
    def GET(self, name):
        if not session.logged:
            raise web.seeother("/")
        return render.add(self, "")
    
    def POST(self, name):
        if not session.logged:
            raise web.seeother("/")
        data = web.input()
        db.insert('blog_posts', title=data.title, text=data.text)
        return render.add(self, "New post was added")

class Logon:
    def GET(self, name):
        return render.logon(self)
    
    def POST(self, name):
        names = web.input()
        session.name = names.login
        if len(names.login) < 1:
            return render.logon(self)
        session.logged = True
        raise web.seeother('/index')        

class Reset:    
    def GET(self, name):
        session.kill();
        raise web.seeother('/index')
    
class Edit:
    _id = 0
    def GET(self, name):
        if not session.logged:
            raise web.seeother("/")
        param = web.input()
        try:
            param = int(param.id)
            data = db.select('blog_posts', where='id='+str(param))
            data = data[0]
            session.current = param
            return render.edit(self, data['title'], data['text'])
        except:
            return render.error(self, 'Error id!')
        
    def POST(self, name):
        param = web.input()
        _id = str(session.get('current', '0'))
        db.update('blog_posts', where="id="+_id, title=param.title, text=param.text) # изменить
        raise web.seeother("/edit?id="+_id)

class Delete:
    def GET(self, name):
        if not session.logged:
            raise web.seeother("/")
        param = web.input()
        try:
            # Переделать, что бы вообще не удалял!!!
            # А то потом начнется, "Дим восстанови, а то я случайно удалил"
            param = int(param.id)
            db.delete('blog_posts', where='id='+str(param))
            raise web.seeother('/')
        except:
            return render.error(self, 'Error id!')
            
class Setting:
    def GET(self, name):
        f = open("./style.xml", "rb")
        tree = etree.parse(f)
        root = tree.getroot()

        params = {}

        for child in root:
            params[child.attrib['name']] = child.text

        f.close()
        return render.setting(self, params)
    
    def POST(self, name):
        param = web.input()
        
        f = open("./style.xml", "rb")
        tree = etree.parse(f)

        root = tree.getroot()
        
        for child in root:
            child.text = param.get(child.attrib['name'], '0')
            print child.text
        
        params = {}
        for child in root:
            params[child.attrib['name']] = child.text
        
        f.close()
        f = open("./style.xml", "w+b")                
        tree.write(f, xml_declaration=True, encoding="utf-8")
        f.close()
        
        fstyle = open("./static/styles/template.css", "rb")
        style = fstyle.read()
        fstyle.close()        
        path = "./static/styles/" + session.get('name', 'anonymous') + "/"
        name = "style.css"

        fstyle = open( path+name,"w+b")
        style = style.format(params['fore-color'], params['titlecolor'], params['postbackcolor'], params['posttextcolor'])
        
        style = style.replace("<", "{")
        style = style.replace(">", "}")
        fstyle.write(style)
        fstyle.close()
        
        return render.setting(self, params)
    
if __name__ == '__main__': 
    app.run()
